/**
 * Created by Asura on 2016/1/25.
 */
var http = require('http'),
    fs = require('fs'),
    socketio = require('socket.io');

var server = http.createServer(function (req, res) {
    fs.readFile('./index.html', 'utf8', function (err, data) {
        if (err) throw err;
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(data, 'utf-8');
    });
}).listen(3000, '127.0.0.1');

var userCount = 0;//用户数，可用于统计站点访问
var io = socketio.listen(server);
io.sockets.on('connection', function (socket) {
    userCount++;
    console.log('user connection');
    socket.on('disconnect', function () {
        userCount--;
        console.log('user disconnection');
        socket.broadcast.emit('message', {
            userCount: userCount,
            msg: 'some on disconnect ,there are ' + userCount + ' user'
        })
    });
    socket.emit('message', {msg: 'You have connected !'});
    socket.broadcast.emit('message', {msg: 'some one connected, there are ' + userCount + ' user'});//广播只会给连接中的发，不会给自己发
    socket.on('asura', function (data) {
        console.log(JSON.stringify(data));
    });
    socket.on('register', function (data, callback) {
        //data是客户端传过来的数据，callback是客户端传过来的回调
        if (data === 0) {
            callback(false);
        } else callback(true);
    });
});
